<script>
import {defineComponent} from 'vue'


export default defineComponent({
    name: "walkInfo",
    data() {
        return {
            localwalkInfo: false,
            isMinimized: false,
            dialogStyle: { top: "82%", left: "82%", transform: "translate(-50%, -50%)",cursor:'pointer' }, // 模态框初始样式
            isDragging: false,
            startX: 0,
            startY: 0,
            offsetX: 0,
            offsetY: 0,
            tableData:[
            ],
            ws:null,
            disabled:false,
            audio:undefined,
            audio_1:undefined,
        };
    },
    methods: {
        close() {
            this.$emit("DialogClose");
            this.dialogStyle = { top: "82%", left: "82%", transform: "translate(-50%, -50%)" ,cursor:'pointer'};
        },
        minimize() {
            this.isMinimized = true;
            this.dialogStyle = {
                top: "auto",
                right: "0",
                bottom: "0",
                width: "200px",
                height: ".9rem",
                transform: "none",
                border: "1px solid #fff",
                fontSize: "12px",
                cursor:'pointer',
                zIndex: 2000,
            };
            this.removeDragListeners();
        },
        restore() {
            this.isMinimized = false;
            this.dialogStyle = { top: "82%", left: "82%", transform: "translate(-50%, -50%)",cursor:'pointer'};
            this.addDragListeners();
        },
        onMouseDown(event) {
            if (this.isMinimized) return;
            this.isDragging = true;
            this.startX = event.clientX;
            this.startY = event.clientY;
            this.offsetX = this.$refs.dialog.offsetLeft;
            this.offsetY = this.$refs.dialog.offsetTop;
            document.body.style.userSelect = "none";
            document.addEventListener("mousemove", this.onMouseMove);
            document.addEventListener("mouseup", this.onMouseUp);
        },
        onMouseMove(event) {
            if (!this.isDragging) return;
            const dx = event.clientX - this.startX;
            const dy = event.clientY - this.startY;
            this.dialogStyle = {
                ...this.dialogStyle,
                left: `${this.offsetX + dx}px`,
                top: `${this.offsetY + dy}px`,
            };
        },
        onMouseUp() {
            this.isDragging = false;
            document.removeEventListener("mousemove", this.onMouseMove);
            document.removeEventListener("mouseup", this.onMouseUp);
            document.body.style.userSelect = "";
        },
        addDragListeners() {
            const dragHandle = this.$refs.dragHandle;
            if (dragHandle) {
                dragHandle.addEventListener("mousedown", this.onMouseDown);
            }
        },
        removeDragListeners() {
            const dragHandle = this.$refs.dragHandle;
            if (dragHandle) {
                dragHandle.removeEventListener("mousedown", this.onMouseDown);
            }
        },
        initTableData() {
            this.tableData = this.walkTableInfo.records
                .filter(item => item.operateType !== "状态检查")
                .map(item => ({
                    ...item,
                    isHandle: "否"
                }));
        },
        start(){
            this.$message.info('开始自动预演......')
            if (!this.disabled){
                this.disabled=true
                this.sendDataSequentially()
                    .then(() => {
                        this.$message.success('自动预演完成');
                    })
                    .catch((error) => {
                        this.$message.error('发送数据时发生错误，请检查网络连接 ');
                    })
                    .finally(() => {
                        this.disabled = false;
                    });
            }
        },
        async sendDataSequentially() {
            for (const data of this.tableData) {
                try {
                    await this.sendData(data);
                    if (data.isHandle === "是") {
                        this.$message.success('操作正确')
                        await this.playAudio(this.audio);
                    } else {
                        this.$message.error('操作错误')
                        await this.playAudio(this.audio_1);
                    }
                } catch (error) {
                    console.error(`发送 ${JSON.stringify(data)} 失败: ${error.message}`);
                    data.isHandle = "否";
                    await this.playAudio(this.audio_1); // 失败时播放 audio_1
                } finally {
                    await this.delay(1000); // 播放完成后再延迟 1 秒进行下一个请求
                }
            }
        },

// 封装音频播放，确保播放完成后才继续
        playAudio(audio) {
            return new Promise((resolve) => {
                if (!audio) {
                    console.warn("音频对象为空，跳过播放");
                    return resolve();
                }
                audio.currentTime = 0; // 每次播放前重置音频进度
                audio.play().then(() => {
                    audio.onended = () => {
                        resolve();  // 音频播放完成后，才继续执行
                    };
                }).catch(err => {
                    console.error("音频播放失败:", err);
                    resolve();  // 如果播放失败，也要继续执行
                });
            });
        },

        delay(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        },

        sendData(data) {
            return new Promise((resolve, reject) => {
                if (this.ws && this.ws.readyState === WebSocket.OPEN) {
                    this.ws.send(JSON.stringify({
                        cmd: 'zypYyStateSwitch',
                        operatePointName: data.operatePointName || '',
                        operateState: data.operateState ?? '',
                        operateType: data.operateType,
                    }));

                    console.log({
                        operatePointName: data.operatePointName || '',
                        operateState: data.operateState ?? '',
                        operateType: data.operateType,
                    });

                    let timeout = setTimeout(() => {
                        this.$message.error('服务器响应超时！');
                        data.isHandle = "否";
                        reject(new Error('服务器响应超时'));
                    }, 15000);

                    this.ws.onmessage = (event) => {
                        let e = JSON.parse(event.data);
                        if (e.cmd === 'zypYyStateSwitch') {
                            clearTimeout(timeout);
                            data.isHandle = "是";
                            resolve();
                        }
                    };
                } else {
                    reject(new Error("WebSocket 未连接"));
                }
            });
        }



    },

    props: {
        walkInfo: {
            type: Boolean,
            default: false,
        },
        walkTableInfo:{
            type: Object,
            default: () => ({}),
        }
    },
    watch: {
        walkInfo(newVal) {
            this.localwalkInfo = newVal;
            if (newVal){
                this.initTableData();
                if (!this.ws){
                    this.ws = this.$store.state.webSocket;
                }
                this.audio = this.$store.state.voiceSet['enable3'] ? new Audio(this.$store.state.voiceSet['sound3']) : null;
                this.audio_1 = this.$store.state.voiceSet['enable4'] ? new Audio(this.$store.state.voiceSet['sound4']) : null;


            }
        },

    },
    mounted() {
        this.$nextTick(() => {
            this.addDragListeners(); // 初始加载时绑定拖动事件
        });


    },
    beforeDestroy() {
        this.removeDragListeners(); // 销毁前移除拖动事件
    },
    computed: {

    },

})
</script>

<template>
    <div v-show="localwalkInfo" class="custom-dialog-wrapper">
        <div
            class="custom-dialog"
            ref="dialog"
            :class="{ 'minimized': isMinimized }"
            :style="dialogStyle">
            <header class="custom-dialog-header" ref="dragHandle" v-if="!isMinimized" style="cursor: move">
                <span>五防预演信息</span>
                <div class="header-buttons">
                    <el-button @click="start" :disabled="disabled">开始自动预演</el-button>
                    <el-button  class="minimize-button" size="medium" @click="minimize" style="border: none;background-color: transparent;color: white" icon="el-icon-caret-bottom">
                    </el-button>
                    <button class="close-button" @click="close" >×</button>
                </div>
            </header>
            <header class="custom-dialog-header" ref="dragHandle" v-if="isMinimized" style="font-size: 14px">
                <span style="margin-top: -1rem">五防预演信息</span>
                <div class="header-buttons">
                    <el-button  size="medium"  class="restore-button" @click="restore" style="border: none;background-color: transparent;color: white;margin-top: -0.8rem" icon="el-icon-caret-top">
                    </el-button>
                </div>
            </header>
            <div class="custom-dialog-content" v-if="!isMinimized">
                <div class="txts" style="overflow-y: auto">
                    <div style="display: flex">
                        <div style="width: 85%;text-align: center;border-right: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 5px 0">操作内容</div>
                        <div style="width: 15%;text-align: center;border-bottom: 1px solid #ccc;padding: 5px 0">是否操作</div>
                    </div>
                    <div v-for="(item,index) in tableData" :key="index" style="display: flex;">
                        <div style="width: 85%;border-bottom: 1px solid #ccc;border-right: 1px solid #ccc;padding: 5px 1rem 0;box-sizing:border-box;white-space: nowrap;overflow-x: auto">{{item.recordDesc}}</div>
                        <div style="width: 15%;text-align:center;border-bottom: 1px solid #ccc;padding: 5px 0;box-sizing: border-box">{{item.isHandle}}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped lang="less">
.custom-dialog-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  pointer-events: none;
  color: #fff;
}

.custom-dialog {
  background: rgb(2, 22, 42);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  pointer-events: auto;
  position: absolute;
  padding: 1rem;
  cursor: move;
  width: 35%;
}


.custom-dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 1.2rem;
  font-weight: bold;
  border-bottom: 1px solid #ebeff0;
  padding-bottom: 0.5rem;
  margin-bottom: 1rem;
}

.header-buttons {
  display: flex;
  gap: 0.5rem;
}

.minimize-button, .restore-button, .close-button {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: white;
}

.custom-dialog-content {
  flex-grow: 1;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  display: flex;
  justify-content: space-between;
}
.txts{
  width: 100%;
  border: 1px solid #ccc;
  height: 15rem;
  overflow: auto;
}
.custom-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}


.table-row {
  display: flex;
  cursor: pointer;
  transition: background-color 0.3s;
}

.table-row:hover {
  background-color: rgb(4, 32, 62); /* 鼠标悬浮时的颜色 */
}

.table-row.selected {
  background-color:rgb(6, 42, 82); /* 选中时的颜色 */
}
.shuyu{
  margin-top: .5rem;
  display: flex;
  justify-content: space-between;
}
.shuyu .el-button{
  color: #ebeff0;
  background: linear-gradient(#176575,#07283f);
  border:0;
  box-shadow: 0 -2px 0 rgba(16, 164, 195, .8);
  margin-left: 0;
}

</style>
